package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.Student;
import service.StudentService;
import utils.Page;

import java.util.List;

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @RequestMapping("/login")
    public String login(Student student)
    {
        boolean flag = studentService.login(student);
        if (flag) {
            return "index";
        }else {
            return "login";
        }
    }
    @RequestMapping("/list/{currentPage}")
    public String list(Student student, @PathVariable("currentPage") Integer currentPage, Model model)
    {
        Page page = new Page();
        int totalCount = studentService.count(student);
        page.setTotalCount(totalCount);
        page.setCurrentPage(currentPage);
        page.setTotalPage();
        //计算偏移量
        int offset = (currentPage - 1) * page.getPageSize();
        List<Student> students = studentService.findAll(student, offset, page.getPageSize());
        //把对象储存在作用域中
        model.addAttribute("page", page);
        model.addAttribute("students", students);
        model.addAttribute("student", student);
        return "student/list";
    }
    @RequestMapping("/toadd")
    public String toadd() {
        return "student/add";
    }

    @RequestMapping("/addSave")
    public String addSave(Student student) {
        int result = studentService.addStudent(student);
        if (result > 0) {
            return "redirect:/student/list/1";
            //重定向
        } else {
            return "student/add";
        }
    }
    @RequestMapping("/delete/{sId}")
    public String delete(@PathVariable("sId") Integer sId) {
        int result = studentService.deleteStudentById(sId);
        if (result > 0) {
            return "redirect:/student/list/1";
            //重定向
        } else {
            return "error";
        }
    }
    @RequestMapping("/toupdate/{sId}")
    public String toUpdate(@PathVariable("sId") Integer sId, Model model) {
        Student student= studentService.findStudentById(sId);
        model.addAttribute("student", student);
        return "student/update";
    }
    @RequestMapping("/updateSave")
    public String update(Student student) {
        int result = studentService.updateStudent(student);
        if (result > 0) {
            return "redirect:/student/list/1";
            //重定向
        } else {
            return "student/update";
        }
    }
}
